#include "ImageManager.h"

void ImageManager::Shutdown() {
    imageWrap.clear();
}

/**
 * ImageManager::Initialize
 * Allocates memory for the ImageWrap array and loads in all the image files.
 */
void ImageManager::Initialize() {
    // Load in all the files
    // void ImageWrap::Setup( string relPath, string sId, int iId )
    AddImage("assets/gfx/default.png", "default");
    AddImage("assets/gfx/stick.png", "stick");
    AddImage("assets/gfx/delphine.png", "player");
    AddImage("assets/gfx/fluffy-grass.png", "grass");
}

/**
 * Push a new image into the vector imageWrap
 * */
void ImageManager::AddImage(const string& relPath, const string& sId) {
    imageWrap.push_back(new ImageWrap(relPath, sId, imageWrap.size()));
}

Image& ImageManager::GetImage(const string& path, const string& id) {
    if (FindImage(id))
        return GetImage(id);
    ImageWrap* img = new ImageWrap(path, id, imageWrap.size());
    imageWrap.push_back(img);

    return img->img;
}

/**
 * Create a new image into the vector imageWrap
 * */
Image& ImageManager::GetImage(const sf::Image &image, const std::string &sId) {
    //if you can find it... return it... else just make one up :))
    if (FindImage(sId))
        return GetImage(sId);

    ImageWrap* img = new ImageWrap(image, sId, imageWrap.size());
    imageWrap.push_back(img);


    return img->img;
}

/**
 * ImageManager::SetImage
 * Returns an Image file based on the string ID given
 */
Image& ImageManager::GetImage(const string& sId) {
    // Search for an image with a matching sId
    int index = FindIndex(sId);

    if (index >= 0)
        return imageWrap[index]->img;
    else
        return imageWrap[0]->img;
}

bool ImageManager::FindImage(const std::string& sId) {
    // Search for an image with a matching sId
    int index = FindIndex(sId);

    if (index >= 0) return true;
    else return false;
}

/**
 * ImageManager::SetImage
 * Returns an Image file based on the integer ID given
 * @return Image corresponding to given id, or the default image if there's an error.
 */
Image& ImageManager::GetImage(unsigned int iId) {
    if (iId < imageWrap.size() && iId >= 0)
        return imageWrap[iId]->img;

    // iId is out of bounds, return default image
    return imageWrap[0]->img;
}

/**
 * Returns the index of the desired asset based on the string passed
 * @param sId string			string identifier of the asset
 * */
int ImageManager::FindIndex(const string& sId) {
    int index = -1;
    for (int i = 0; i < (int) imageWrap.size(); i++) {
        if (imageWrap[i]->sId == sId) {
            index = i;
            break;
        }
    }

    return index;
}
